package org.atf.model.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;

import org.atf.model.entity.Audit;
import org.atf.model.entity.Preference;
import org.atf.model.entity.User;
import org.atf.model.utils.EntityManagerUtil;


public class UserDAO {
	public void insertUser(User user){
		EntityManager entityManager = EntityManagerUtil.getEntityManager();
		try{
			entityManager.getTransaction().begin();
			entityManager.persist(user);
			entityManager.getTransaction().commit();
		}finally {
		//	entityManager.close();
		}
	}
	public List<User> getAllUser(){	
		EntityManager entityManager=EntityManagerUtil.getEntityManager();
		Query query = entityManager.createQuery("select u from User u ");	
		List<User> resultList = query.getResultList();
		return resultList;
	}
	public void deleteUser(Integer id){
		EntityManager entityManager = EntityManagerUtil.getEntityManager();
		 try{
				entityManager.getTransaction().begin();
				User user=entityManager.find(User.class, id);
				entityManager.remove(user);
				entityManager.flush();
				entityManager.getTransaction().commit();
		 } finally {
		//	 entityManager.close();
		 }	
	}
	public void updateUser(User user){
		EntityManager entityManager = EntityManagerUtil.getEntityManager();
		try{
			entityManager.getTransaction().begin();
			entityManager.merge(user);
			entityManager.getTransaction().commit();
		}finally {
		//	entityManager.close();
		}
	}

	public User getUserByName(String username){
		EntityManager entityManager = EntityManagerUtil.getEntityManager();
		User user = null;
		try{
			user =
					entityManager.createNamedQuery("User.findUserByName", User.class)
					.setParameter("username", username)
					.getSingleResult();
		}catch (NoResultException e){
			user= null;
		}finally {
		//	entityManager.close();
		}
		return user;
	}
	
	
	public User getUserByNamePassword(String username, String password){
		EntityManager entityManager = EntityManagerUtil.getEntityManager();
		User user = null;
		try{
			Query query = entityManager.createQuery("select u from User u ");
			List<User> resultList = query.getResultList();
			System.out.println(resultList);
			user =
					entityManager.createNamedQuery("User.findUserByNamePassword", User.class)
					.setParameter("username", username)
					.setParameter("password", password)
					.getSingleResult();
		}catch (NoResultException e){
			user= null;
		}finally {
		//	entityManager.close();
		}
		return user;
	}
}
